<template>
  <div class="app-container bg-white border-[1px] border-[#dcdfe6]">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" label-position="left">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="标题" label-width="auto">
            <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="作者" label-width="auto">
            <el-input v-model="searchForm.author" placeholder="请输入作者" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="4" v-show="isExpand">
          <el-form-item label="评级" label-width="auto">
            <el-select v-model="searchForm.rating" placeholder="请选择评级" clearable>
              <el-option v-for="item in ratingOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="isExpand ? 6 : 12">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button link @click="toggleExpand">{{ isExpand ? '收起' : '展开' }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>


    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除</el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="warning" @click="handleImport">导入</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" element-loading-text="数据加载中..."
      @selection-change="handleSelectionChange" border max-height="532px">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 + (pagination.currentPage - 1) * pagination.pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="tenant_id" label="租户ID" />
      <el-table-column prop="device_name" label="设备名" />
      <el-table-column prop="device_sn" label="设备SN" />
      <!--
      <el-table-column prop="rating" label="评级">
        <template #default="{ row }">
          <el-tag :type="ratingTagType[row.rating]">
            {{ratingOptions.find(item => item.value === row.rating)?.label}}
          </el-tag>
        </template>
      </el-table-column>
      -->
      <el-table-column prop="ip" label="IP" />
      <el-table-column prop="port" label="端口" />
      <el-table-column prop="switch" label="开关">
        <template #default="{ row }">
          <el-switch v-model="row.switch" @change="handleSwitchChange(row)" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="时间" :formatter="(row: any) => formatTime(row.created_at)" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button type="primary" size="small" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
          <el-button type="info" size="small" link @click="handleView(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination class="pagination" v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]" :background="true"
      layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增数据' : '编辑数据'" width="600px"
      @closed="handleClosed">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="设备名称" prop="device_name">
          <el-input v-model="formData.device_name" placeholder="请输入设备名称" />
        </el-form-item>
        <!--
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="评级" prop="rating">
          <el-select v-model="formData.rating" placeholder="请选择评级">
            <el-option v-for="item in ratingOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="formData.quantity" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" />
        </el-form-item>
        -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="submitForm(formRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer v-model="drawerVisible" title="详情展示" direction="rtl" size="40%">
      <el-descriptions :column="1" border v-if="currentRow">
        <el-descriptions-item label="标题">{{ currentRow.title }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ currentRow.author }}</el-descriptions-item>
        <el-descriptions-item label="评级">
          <el-tag :type="ratingTagType[currentRow.rating]">
            {{ratingOptions.find(item => item.value === currentRow?.rating)?.label}}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentRow.quantity }}</el-descriptions-item>
        <el-descriptions-item label="开关状态">
          <el-tag :type="currentRow.switch ? 'success' : 'danger'">
            {{ currentRow.switch ? '开启' : '关闭' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRow.status ? 'success' : 'danger'">
            {{ currentRow.status ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentRow.createTime }}</el-descriptions-item>
      </el-descriptions>
      <div class="drawer-footer" v-if="currentRow">
        <el-button @click="drawerVisible = false">关闭</el-button>
      </div>
    </el-drawer>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, useTemplateRef, onMounted } from 'vue'
import { FormInstance, FormRules, ElDrawer, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { $message } from '@/utils/message'
import { formatTime } from '@/utils/day'
import Request from '@/request'

// 新增抽屉相关状态
const drawerVisible = ref(false)
const currentRow = ref<TableItem | null>(null)

// 查看详情
const handleView = (row: TableItem) => {
  currentRow.value = row
  drawerVisible.value = true
}


// 新增折叠状态
const isExpand = ref(false)

// 切换折叠状态
const toggleExpand = () => {
  if (isExpand.value) {
    searchForm.rating = null  // 收起时清空评级条件
  }
  isExpand.value = !isExpand.value
}

// 修改重置方法
const resetSearch = () => {
  searchForm.title = ''
  searchForm.author = ''
  searchForm.rating = null
  isExpand.value = false  // 重置时关闭展开状态
  handleSearch()
}

interface TableItem {
  id: number
  title: string
  author: string
  rating: number
  quantity: number
  switch: boolean
  status: boolean
  createTime: string
}

// 搜索表单
const searchForm = reactive({
  title: '',
  author: '',
  rating: null as number | null
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const multipleSelection = ref([])
const getTableData = () => {
  loading.value = true
  Request.post('device/list').then(response => {
    const { data } = response
    tableData.value = data
    loading.value = false
  }).catch(error => {
    console.error(error)
    loading.value = false
  })
}

// 对话框相关
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
interface FormData {
  id?: number | string,
  device_name: string
}
const formData = reactive<FormData>({
  device_name: '',
  /*author: '',
  rating: 1,
  quantity: 0,
  switch: true,
  status: true*/
})

// 表单验证规则
const formRules = reactive<FormRules<FormData>>({
  device_name: [{ required: true, message: '请输入设备名称', trigger: ['blur', 'change'] }],
  /*author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  rating: [{ required: true, message: '请选择评级', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]*/
})

// 评级选项
const ratingOptions = [
  { value: 1, label: '一级' },
  { value: 2, label: '二级' },
  { value: 3, label: '三级' }
]

const ratingTagType = ['', 'warning', 'danger'];

// 初始化数据
/*
onMounted(() => {
  loadTableData()
})

// 加载表格数据
const loadTableData = async () => {
  // 这里替换为实际API调用
  const mockData: TableItem[] = Array.from({ length: 50 }, (_, i) => ({
    id: i + 1,
    title: `标题 ${i + 1}`,
    author: `作者 ${i % 5}`,
    rating: (i % 3) + 1,
    quantity: Math.floor(Math.random() * 100),
    switch: i % 2 === 0,
    status: i % 3 !== 0,
    createTime: new Date().toLocaleString()
  }))

  // 模拟分页
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  tableData.value = mockData.slice(start, end)
  pagination.total = mockData.length
}*/

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  //loadTableData()
}


// 分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  //loadTableData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  //loadTableData()
}

// 表格多选
const handleSelectionChange = (val: TableItem[]) => {
  //multipleSelection.value = val
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  /*
  Object.assign(formData, {
    title: '',
    author: '',
    rating: 1,
    quantity: 0,
    status: true
  })*/
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: FormData) => {
  const { id, device_name } = row
  dialogType.value = 'edit'
  Object.assign(formData, {
    id,
    device_name
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      // 新增
      if (dialogType.value === 'add') {
        Request.post('device/create', formData).then(() => {
          dialogVisible.value = false
          saveLoading.value = false
          $message.success('添加成功')
          getTableData()
        }).catch(() => {
          saveLoading.value = false
        })
      } else {
        // 编辑
      }
    }
  })
  //await formRef.value.validate()

  // 这里添加实际提交逻辑
  // dialogVisible.value = false
  //await loadTableData()
}

const handleClosed = () => {
  formRef.value?.resetFields()
}

// 删除
const handleDelete = (row: TableItem) => {
  // 这里添加实际删除逻辑
  console.log(row)
  //loadTableData()
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    $message.warning('请选择要删除的数据')
    return
  }
  // 这里添加实际批量删除逻辑
  //loadTableData()
}

// 导出
const handleExport = () => {
  // 导出逻辑
}

// 导入
const handleImport = () => {
  // 导入逻辑
}

// 开关状态变化
const handleSwitchChange = (row: TableItem) => {
  console.log(row)
  // 这里添加开关状态更新逻辑
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 新增抽屉样式 */
.drawer-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-descriptions__body) {
  padding: 20px;
}

:deep(.el-descriptions__label) {
  width: 100px;
  text-align: right;
}
</style>